package rabbitmq;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.MessageProperties;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @Author: DRevelation
 * @Date: 2021/4/28 14:35
 */
public class ProducerDemo {

    private static final String IP_ADDRESS = "127.0.0.1";
    private static final Integer PORT = 5672;
    private static final String USERNAME = "admin";
    private static final String PASSWORD = "111111";

    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(IP_ADDRESS);
        factory.setPort(PORT);
        factory.setUsername(USERNAME);
        factory.setPassword(PASSWORD);
        Connection conn = factory.newConnection();
        Channel channel = conn.createChannel();

        // 创建交换器：direct、持久化、不自动删除
        channel.exchangeDeclare("ex-01", "direct", true, false, null);
        // 创建队列：持久化、非排他、非自动删除的队列
        channel.queueDeclare("queue-01", true, false, false, null);
        // 将交换器与队列通过路由键绑定
        channel.queueBind("queue-01", "ex-01", "rt-01");

        for (int i = 0; i < 3; i++) {
            String msg = "呃呃呃 RabbitMQ: " + i;
            channel.basicPublish("ex-01", "rt-01", MessageProperties.PERSISTENT_TEXT_PLAIN, msg.getBytes());
        }
        channel.close();
        conn.close();
    }
}
